上一篇我們已經完成了 飯店搜尋 API 的撰寫,接下來只需要把它改寫成 Sub-Agent,就能讓 Master Agent 寫好後在調度時呼叫使用了。
這個這篇的重點是:
search_hotels
) 轉換成 ADK 格式的 Sub-Agent。匯入模組 與 prompt.py
from fastapi import HTTPException
from google.adk.agents import Agent
from . import prompt
建立模擬的飯店資料庫
# 模擬飯店資料庫
HOTEL_DATABASE = {
"Taipei": [
{"name": "Taipei Grand Hotel", "stars": 5, "price": 4000},
{"name": "Hotel Proverbs Taipei", "stars": 4, "price": 3000},
{"name": "Cosmos Hotel Taipei", "stars": 3, "price": 2000},
{"name": "Caesar Park Hotel", "stars": 4, "price": 3500},
],
"Tokyo": [
{"name": "Park Hyatt Tokyo", "stars": 5, "price": 50000},
{"name": "Shinjuku Granbell Hotel", "stars": 4, "price": 20000},
{"name": "Hotel Sunroute Plaza", "stars": 3, "price": 15000},
],
"New York": [
{"name": "The Plaza", "stars": 5, "price": 700},
{"name": "Pod 51 Hotel", "stars": 3, "price": 200},
{"name": "Arlo SoHo", "stars": 4, "price": 350},
],
}
Sub-Agent 的工具函式(Tool Function)
把原本的 API function 改成 可被 Agent 使用的工具:
def search_hotels(request: dict) -> dict:
"""
呼叫飯店搜尋 Agent,根據城市名稱回傳最多 3 家飯店資料。
"""
try:
# city = city.strip()
city = request.get("city", "").strip()
if not city:
raise ValueError("City name is required.")
hotels = HOTEL_DATABASE.get(city, [])
result = hotels[:3]
if not result:
return {"status": "error", "message": f"No hotels found for city '{city}'."}
return {"status": "success", "city": city, "hotels": result}
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {e}")
功能摘要:
request
中取出 cityhotel_search_agent = Agent(
name="hotel_search_agent",
model="gemini-2.5-flash",
description=prompt.HOTEL_SEARCH_AGENT_DESCRIPTION,
instruction=prompt.HOTEL_SEARCH_AGENT_INSTRUCTION,
tools=[search_hotels],
)
name
:Sub-Agent 的名稱model
:指定要用的模型(這裡使用 gemini-2.5-flash)description
與 instruction
:寫好的 Prompttools
:掛上工具(也就是 search_hotels
function)Prompt 分成兩個部分:
description
:描述這支 Agent 是做什麼的,這裡是負責搜尋飯店,並依據城市回傳結果。
HOTEL_SEARCH_AGENT_DESCRIPTION = """
This is a hotel search sub-agent that retrieves hotel information based on a given city.
"""
instruction
:詳細指令,告訴 Agent 該怎麼做。
HOTEL_SEARCH_AGENT_INSTRUCTION = """
You are a hotel search agent responsible for retrieving hotel data.
Your responsibilities:
- Accept a city name as input.
- Query the internal database and return up to 3 hotels.
- Each hotel must include name, price, and rating.
- If no hotels are found for the city, return a clear error message.
Respond with a concise and structured hotel list.
"""